package com.yupi.yuojcodesandbox;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
//import com.sun.javaws.IconUtil;
import com.yupi.yuojcodesandbox.Utils.ProcessUtils;
import com.yupi.yuojcodesandbox.model.ExecuteCodeRequest;
import com.yupi.yuojcodesandbox.model.ExecuteCodeResponse;
import com.yupi.yuojcodesandbox.model.ExecuteMessage;
import com.yupi.yuojcodesandbox.model.JudgeInfo;
import org.apache.tomcat.jni.Proc;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
public class JavaNativeCodeSandboxImpl implements CodeSandbox {

    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    private static final long TIME_OUT = 5000L;

    private static final List<String> blackList = Arrays.asList("Files" , "exec");

    //字典树
    public static final WordTree WORD_TREE;

    static {
        WORD_TREE = new WordTree();
        WORD_TREE.addWords(blackList);
    }
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();

        //校验代码有没有木马
        //!!!
        FoundWord foundWord = WORD_TREE.matchWord(code);
        if(foundWord != null){
            System.out.println("有敏感词 : " + foundWord);
            return null;
        }

        //1.获取当前的根目录 yuoj-codesandbox
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;


        //没有文件则新建
        if(!FileUtil.exist(globalCodePathName)){
            FileUtil.mkdir(globalCodePathName);
        }


        //把用户的代码保存为临时文件!!! UUID
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code , userCodePath , StandardCharsets.UTF_8);


        //2.程序自动使用javac编译代码，得到class文件
        String compileCmd = String.format("javac -encoding utf-8 %s" , userCodeFile.getAbsolutePath());
        try {
            //!!!
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            //获得编译的结果
            ProcessUtils.runProcessAndGetMessage(compileProcess , "Compile");
        } catch (IOException e) {
            return getErrorResponse(e);
        }

        //3.程序执行代码，得到输出结果
        List<ExecuteMessage> executeMessageList = new ArrayList<>();

        for(String inputArgs : inputList){

            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s" , userCodeParentPath , inputArgs);
            try {
                Process runProcess = Runtime.getRuntime().exec(runCmd);
                //守护线程
                new Thread(()->{
                    try {
                        Thread.sleep(TIME_OUT);
                        runProcess.destroy();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }).start();

                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess , "Run");
                executeMessageList.add(executeMessage);
            } catch (IOException e) {
                return getErrorResponse(e);

            }
        }


        //4.收集整理输出结果
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        //取最大运行世界，判断是否超时
        long maxTime = 0;
        for(ExecuteMessage executeMessage : executeMessageList){
            String errorMessage = executeMessage.getErrorMessage();
            if(StrUtil.isNotBlank(errorMessage)){
                executeCodeResponse.setMessage(errorMessage);
                //执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long runTime = executeMessage.getTime();
            if(runTime != null){
                maxTime = Math.max(maxTime , runTime);
            }

        }
        if(outputList.size() == executeMessageList.size()){
            executeCodeResponse.setStatus(0);
        }
        executeCodeResponse.setOutputList(outputList);

        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);

        //运行内存太麻烦，不做实现
        judgeInfo.setMemory(1000L);
        executeCodeResponse.setJudgeInfo(judgeInfo);


        //5.清理生成的临时文件
        if(userCodeFile.getParentFile() != null){
            boolean del = FileUtil.del(userCodeParentPath);
            if(del){
                System.out.println("delete succeed!");
            }else{
                System.out.println("delete failed!");
            }
        }



        return executeCodeResponse;
    }

    /**
     * 获取错误响应
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e){
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        //表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }


    public static void main(String[] args) {
        //模拟yuoj——backend发来的请求  ExecuteCodeRequest
        JavaNativeCodeSandboxImpl javaNativeCodeSandbox = new JavaNativeCodeSandboxImpl();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1 2"));
        String code = ResourceUtil.readStr("simpleComputeArgs/Main.java" , StandardCharsets.UTF_8);
        executeCodeRequest.setCode(code);;
        executeCodeRequest.setLanguage("java");
        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);
    }
}
